#include <iostream>
#include <thread>
#include <vector>
#include <atomic>

class TicketSystem {
public:
    TicketSystem(int total) : tickets(total) {}

    bool sellTicket() {
        int old = tickets.fetch_sub(1, std::memory_order_relaxed);
        if (old <= 0) {
            return false;
        }
        std::cout << "售出1张票，剩余: " << (old - 1)
                  << " (线程ID: " << std::this_thread::get_id() << ")\n";
        return true;
    }

private:
    std::atomic<int> tickets;
};

int main() {
    const int TOTAL = 10000, THREADS = 10;
    TicketSystem sys(TOTAL);
    std::vector<std::thread> vt;
    for (int i = 0; i < THREADS; ++i)
        vt.emplace_back([&]{ while (sys.sellTicket()); });
    for (auto &t : vt) t.join();
    return 0;
}
